# -*- coding: utf-8 -*-

from w.blocks.containers.block import Block

from w.html.doctypes.preferable import Select as SelectTag
from w.html.doctypes.preferable import Optgroup, Option

class Select(Block):
    def __init__(self, content=None, selected=None, *argv, **kwargv):
        self.groups = {}
        self.indexize = False
        if isinstance(content, dict):
            self.groups = content
            Block.__init__(self, [], *argv, **kwargv)
            content = [0]
            if isinstance(self.groups.values()[0][0], list) or \
               isinstance(self.groups.values()[0][0], tuple):
                self.indexize = True
        else:
            Block.__init__(self, content, *argv, **kwargv)
            if isinstance(content[0], tuple) or isinstance(content[0], list):
                self.indexize = True

        self.selected = selected
        self.tag = SelectTag(*argv, **kwargv)
        self.html = self.tag.html

    def wrapInOption(self, value, ind=None):
        if self.selected == value and ind != None:
            return Option(value, hselected=True, hvalue=ind)
        elif ind != None:
            return Option(value, hvalue=ind)
        return Option(value)

    def wrapInGroup(self, name, valueList):
        if self.indexize:
            return Optgroup([self.wrapInOption(v[0], v[1]) for v in valueList], hlabel=name)
        return Optgroup([self.wrapInOption(v) for v in valueList], hlabel=name)

    def make(self, content=[]):
        if self.groups:
            self.tag.extend([self.wrapInGroup(g,os) for g,os in self.groups.items()])
        else:
            if not content:
                content = self
        if self.indexize:
            self.tag.extend([self.wrapInOption(c[0], c[1]) for c in content])
        else:
            self.tag.extend([self.wrapInOption(c) for c in content])
        return Block.make(self, [self.tag])

